import axios, { AxiosError } from 'axios'
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'
import { AxiosCanceler, checkStatus, ResultEnum } from './helper'
import type { Result } from './interface'
import router from '@/router'
import useGlobalStore from '@/store/modules/global'
import { ElMessage } from 'element-plus'

/**
 * pinia 错误使用说明
 * https://github.com/vuejs/pinia/discussions/971
 * https://github.com/vuejs/pinia/discussions/664#discussionco mment-1329898
 * https://pinia.vuejs.org/core-concepts/outside-component-usage.html#single-page-applications
 */

const axiosCanceler = new AxiosCanceler()

const config = {
  // 设置超时时间（10s）
  timeout: ResultEnum.TIMEOUT as number,
  // 跨域时候允许携带凭证
  withCredentials: true
}

class RequestHttp {
  service: AxiosInstance
  public constructor(config: AxiosRequestConfig) {
    // 实例化axios
    this.service = axios.create(config)

    /**
     * @description 请求拦截器
     * 客户端发送请求 -> [请求拦截器] -> 服务器
     * token校验(JWT) : 接受服务器返回的token,存储到vuex/本地储存当中
     */
    this.service.interceptors.request.use(
      (config: AxiosRequestConfig) => {
        const globalStore = useGlobalStore()
        // * 将当前请求添加到 pending 中
        // config.headers = { Authorization: globalStore.token || localStorage.getItem('tokenMediaPlat') || '', }
        config.headers = { Authorization: globalStore.token }
        axiosCanceler.addPending(config)
        return {
          ...config
        }
      },
      (error: AxiosError) => {
        return Promise.reject(error)
      }
    )

    /**
     * @description 响应拦截器
     *  服务器换返回信息 -> [拦截统一处理] -> 客户端JS获取到信息
     */
    this.service.interceptors.response.use(
      (response: AxiosResponse) => {
        const { data, config } = response
        // * 在请求结束后，移除本次请求
        axiosCanceler.removePending(config)
        // * 登陆失效（code == 500）
        if (data.code === ResultEnum.OVERDUE) {
          ElMessage.error(data.msg)
          router.replace({
            path: '/'
          })
          return Promise.reject(data)
        }
        // * 成功请求
        return data
      },
      async (error: AxiosError) => {
        const globalStore = useGlobalStore()
        const { response } = error
        const data: Result = response?.data as Result

        if (data) {
          ElMessage.error(data.msg)
          // checkStatus(`${response?.status}`)
          if (data.code == '401') {
            globalStore.setToken('')
            router.push('/')
          }
        } else {
          // 根据响应的错误状态码，做不同的处理
          checkStatus(`${response?.status}`)
        }

        return Promise.reject(error)
      }
    )
  }

  // * 常用请求方法封装
  get<T>(url: string, params?: object, _object = {}): Promise<T> {
    return this.service.get(url, { params, ..._object })
  }
  post<T>(url: string, params?: object, _object = {}): Promise<T> {
    return this.service.post(url, params, _object)
  }
  put<T>(url: string, params?: object, _object = {}): Promise<T> {
    return this.service.put(url, params, _object)
  }
  delete<T>(url: string, params?: object): Promise<T> {
    return this.service.delete(url, { data: params })
  }
  download(url: string) {
    return axios.get(url, { responseType: 'blob', headers: { 'subscription-key': '' } })
  }
}

export default new RequestHttp(config)
